package top.lgd.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import top.lgd.base.CacheKeys;
import top.lgd.base.LgdConstants;
import top.lgd.base.LgdException;
import top.lgd.base.LgdTable;
import top.lgd.pojo.entity.system.User;
import top.lgd.service.LgdCacheService;
import top.lgd.utils.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


/**
 *
 */
@RestController
public class LgdController {

    @Autowired
    private HttpServletRequest httpServletRequest;
    @Autowired
    protected LgdCacheService lgdCacheService;

    @GetMapping("/isAlive")
    public boolean isAlive() {
        return true;
    }

    protected User checkCurrentUser() {
        final String token = httpServletRequest.getHeader(LgdConstants.AUTHORIZATION);
        if (StringUtils.isNotEmpty(token)) {
            return lgdCacheService.getAndRenew(CacheKeys.CURRENT_USER + token);
        }
        return null;
    }

    /**
     * 响应请求分页数据
     */
    protected <T> LgdTable<T> getTable(Page<T> page) {
        return getTable(page, page.getRecords());
    }

    /**
     * 响应请求分页数据
     */
    protected <T> LgdTable<T> getTable(List<T> list) {
        return new LgdTable(1L, 1L, 1L, list);
    }

    /**
     * 响应请求分页数据
     */
    protected <T> LgdTable<T> getTable(Page page, List<T> data) {
        return new LgdTable(page.getCurrent(), page.getSize(), page.getTotal(), data);
    }

    protected User current() {
        User user = checkCurrentUser();
        if (null != user) {
            return user;
        } else {
            throw new LgdException("会话失效");
        }

    }
}